package com.shuda.business.user.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shuda.business.user.entity.UserRoleEntity;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色关联Mapper接口
 */
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRoleEntity> {

    /**
     * 根据用户ID获取角色ID列表（默认实现，避免XML缺失导致的编译错误）
     * @param userId 用户ID
     * @return 角色ID列表
     * @author ink
     * @Description: 使用LambdaQueryWrapper查询userId对应的角色ID列表
     * @date 2025-11-09 11:30
     */
    default List<Long> selectRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        List<UserRoleEntity> records = this.selectList(wrapper);
        return records.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList());
    }

    /**
     * 删除用户的角色关联（默认实现，避免XML缺失）
     */
    default int deleteByUserId(Long userId) {
        LambdaQueryWrapper<UserRoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRoleEntity::getUserId, userId);
        return this.delete(wrapper);
    }

    /**
     * 批量插入用户角色关联（默认实现）
     */
    default int batchInsert(Long userId, List<Long> roleIds) {
        if (roleIds == null || roleIds.isEmpty()) {
            return 0;
        }
        int count = 0;
        for (Long roleId : roleIds) {
            UserRoleEntity entity = new UserRoleEntity();
            entity.setUserId(userId);
            entity.setRoleId(roleId);
            count += this.insert(entity);
        }
        return count;
    }
}